import json
import os
import shutil

from common.cleaner import clear
from common.common import execute_cmd, execute_cmd_list, check_command_injection, ismount_with_timeout
from common.parse_parafile import ParamFileUtil
from common.util.check_utils import is_ip_address, is_port
from exchange.common.const import ExchangeSupportVersion, ErrorCode, CmdRetCode, CMDResult, GroupCheckType, \
    ExchangeResourceKeyName
from exchange.common.exchange_client import ExchangeClient
from exchange.common.exchange_common import exec_sql_cmd, get_env_variable, check_special_characters, check_mount
from exchange.common.exchange_exception import ErrCodeException
from exchange.logger import log


class ExchangeResourceInfo:

    def __init__(self, pid):
        self.pid = pid
        try:
            self.param = ParamFileUtil.parse_param_file(self.pid)
        except Exception as err:
            raise Exception(f"Failed to parse job param file for {err}") from err
        if not self.param:
            raise Exception(f"Failed to parse job param file is none")
        log.info(f"ExchangeResourceInfo param:{self.param}")
        try:
            self.client = ExchangeClient(self.pid, self.param)
        except Exception as exception_str:
            log.error(f"ExchangeClient init failed.{exception_str}")

    def get_version(self):
        query_version = ""
        try:
            query_version = self.client.get_exchange_version()
        except Exception as exception_str:
            log.error(f"query_group_version failed.{exception_str}")
        for version in ExchangeSupportVersion:
            if query_version == version:
                log.info(f"Get group version {query_version} success!")
                return True, query_version
        log.error("Exchange version not supported")
        return False, query_version

    def check_connectivity(self):
        log.info("check_connectivity")
        try:
            self.client.get_exchange_version()
        except Exception as exception_str:
            log.error(f"check_connectivity failed.{exception_str}")
        log.info("check_connectivity success")
        return True

    def get_info(self):
        log.info("get_information")
        information = dict()
        try:
            information["version"] = self.client.get_exchange_version()
            information["server_name"] = self.client.get_exchange_server_name()
            information["server_role"] = self.client.get_exchange_server_role()
            information["server_config"] = self.client.get_exchange_server_config()
        except Exception as exception_str:
            log.error(f"get_information failed.{exception_str}")
            return False, information
        log.info("get_information success")
        return True, information
